package net.tarine.gastronomi.server.persistence;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import net.tarine.gastronomi.server.model.GasUser;
import net.tarine.gastronomi.shared.Role;

import com.google.appengine.api.users.User;

public class GasUserDao {
	
	@SuppressWarnings("unchecked")
	public static List<GasUser> findGasUsers(PersistenceManager pm, int offset, int pageSize) {
		Query query = pm.newQuery(GasUser.class);
		query.setOrdering("nickname ascending");
		query.setRange(offset, offset + pageSize);
		List<GasUser> results = (List<GasUser>) query.execute();
		return results;
	}

	@SuppressWarnings("unchecked")
	public static GasUser findGasUserByUserId(PersistenceManager pm, String userId) {
		Query query = pm.newQuery(GasUser.class,
		        "userId == p1 ");
	    query.declareParameters("String p1");
	    List<GasUser> result = (List<GasUser>) query.execute(userId);
	    if (result != null) {
		    if (result.size() > 0) {
		    	return result.get(0);
		    }
	    }
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public static GasUser findGasUserByEmail(PersistenceManager pm, String email) {
		Query query = pm.newQuery(GasUser.class,
		        "email == p1 ");
	    query.declareParameters("String p1");
	    //query.setUnique(true);
	    List<GasUser> result = (List<GasUser>) query.execute(email);
	    if (result != null) {
		    if (result.size() > 0) {
		    	return result.get(0);
		    }
	    }
		return null;
	}
	
	public static GasUser createGasUserFromGoogleUser(PersistenceManager pm, User user, boolean admin) {
        //persist gasUser
		GasUser gasUser = new GasUser();
		gasUser.setUserId(user.getUserId());
		gasUser.setUser(user);
		gasUser.setEmail(user.getEmail());
		gasUser.setNickname(user.getNickname());
		gasUser.setRoleId(Role.ALIEN.getId());
		if (admin) {
			gasUser.setRoleId(Role.ADMIN.getId());
		}
		gasUser = pm.makePersistent(gasUser);
		return gasUser;
	}
	
	public static GasUser enrichGasUserFromGoogleUser(PersistenceManager pm, GasUser gasUser, User user, boolean admin) {
        //persist gasUser
		//GasUser gasUser = findGasUserByUserId(pm, user.getUserId());
		if (gasUser == null) return null;
		gasUser.setUser(user);
		gasUser.setUserId(user.getUserId());
		gasUser.setEmail(user.getEmail());
		gasUser.setNickname(user.getNickname());
		gasUser = pm.makePersistent(gasUser);
		return gasUser;
	}
}
